package com.example.transaction_service_b.common;

import com.example.transaction_service_b.service.EventProcessService;
import com.example.transaction_service_b.service.EventPublishService;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.core.annotation.Order;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Map;

/**
 * Created by Administrator on 2017/5/18.
 */
@Component
public class Receiver implements MessageListener {

    @Autowired
    private EventProcessService eventProcessService;

    @Autowired
    private EventPublishService eventPublishService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void onMessage(Message message) {
        try {
            Map<String, Object> maps = convert(message.getBody(),Map.class);
            System.out.println("服务B接收到事务消息1[" + new Date() + "]=======" + maps);
            if(eventPublishService.updateVersion(maps)){//解决幂等性
                if (eventProcessService.insertData(maps)){
                    System.out.println("接受到的事务消息插入成功");
                } else {
                    System.out.println("接受到的事务消息插入失败");
                }
            } else {
                System.out.println("系统判断此消息已被其他同类型服务器处理，所以丢弃");
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("事务处理手抛异常");
        }
    }

    public <T> T convert(byte[] bytes,Class<T> clazz) throws IOException, ClassNotFoundException {
        ByteArrayInputStream byteArrayInputStream = null;
        ObjectInputStream oi=null;
        try{
            byteArrayInputStream = new ByteArrayInputStream(bytes);
            oi= new ObjectInputStream(byteArrayInputStream);
            return (T)oi.readObject();
        }catch (Exception e){
            throw e;
        }finally {
            try {
                byteArrayInputStream.close();
                oi.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
